<template>
  <div class="schedule-center">
    <div v-if="!showJobCenter" class="add-worker-row">
      <button @click="getRegisterUrl">add worker node</button>
      <div v-if="registerUrl" class="url-display">
        <div>URL: {{ registerUrl.url }}</div>
        <div>过期时间: {{ formattedTimeout }}</div>
      </div>
    </div>
    
    <WorkerNodeList 
      v-if="!showJobCenter"
      :env_id="env_id" 
      @show-job-details="showJobDetails"
    />
    
    <JobCenter 
      v-if="showJobCenter" 
      :env_id="env_id" 
      :worker_id="selectedWorkerId"
      @go-back="hideJobDetails"
    />
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { getRegisterUrl } from '../../api/workerNodes'
import WorkerNodeList from './WorkerNodeList.vue'
import JobCenter from '../jobs/JobCenter.vue'

export default {
  components: { WorkerNodeList, JobCenter },
  props: {
    env_id: {
      type: String,
      required: true
    }
  },
  setup() {
    const registerUrl = ref(null)
    const showJobCenter = ref(false)
    const selectedWorkerId = ref('')

    const formattedTimeout = computed(() => {
      if (!registerUrl.value) return ''
      const date = new Date(registerUrl.value.timeout * 1000)
      return date.toLocaleString()
    })

    const getRegisterUrlHandler = async () => {
      try {
        const data = await getRegisterUrl()
        registerUrl.value = data
      } catch (error) {
        console.error('Failed to get register URL:', error)
      }
    }

    const showJobDetails = (worker_id) => {
      selectedWorkerId.value = worker_id
      showJobCenter.value = true
    }

    const hideJobDetails = () => {
      showJobCenter.value = false
    }

    return {
      registerUrl,
      formattedTimeout,
      showJobCenter,
      selectedWorkerId,
      getRegisterUrl: getRegisterUrlHandler,
      showJobDetails,
      hideJobDetails
    }
  }
}
</script>

<style scoped>
.url-display {
  display: contents;
}

.add-worker-row {
  display: flex;
}

.add-worker-row button {
  padding: 10px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  margin-bottom: 20px;
  cursor: pointer;
}

.add-worker-row button:hover {
  opacity: 0.9;
}
</style>